
/*
 * @Description: 流程分类
 * @Author: DHL
 * @Date: 2022-08-19 15:43:19
 * @LastEditors: DHL
 * @LastEditTime: 2022-08-23 13:51:54
 */

import { defineComponent, computed, reactive, ref } from 'vue'
import { log } from '/@/utils/log'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { FlowCategoryModel } from '/@/api/flow/model/flowCategoryModel'
import { apiFlowCategorySave, apiFlowCategorySearchTree, apiFlowCategoryUpdateById } from '/@/api/flow/flowCategory'
import { arrayLastValue } from '/@/utils/twUtils'

export default defineComponent({
  name: 'FlowCategoryForm',
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    /**
     * 公共
     */
    const state = reactive({ pid: '' })

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      id: '',  // 主键
      pid: '',  // 父级ID
      name: '',  // 名称
      code: '',  // 编码
      shortName: '',  // 简称
      seq: 0,  // 排序号
      state: '1',  // 状态（字典：FLOW_CATEGORY_STATE）
      remark: ''  // 备注
    }

    let dbForm = reactive<FlowCategoryModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      pid: [
        {
          required: false,
          message: '请选择父级',
          trigger: 'blur'
        }, {
          max: 50,
          message: '最多可输入50个字符',
          trigger: 'blur'
        }
      ],
      name: [
        {
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }, {
          max: 200,
          message: '最多可输入200个字符',
          trigger: 'blur'
        }
      ],
      code: [
        {
          required: true,
          message: '请输入编码',
          trigger: 'blur'
        }, {
          max: 50,
          message: '最多可输入50个字符',
          trigger: 'blur'
        }
      ],
      shortName: [
        {
          required: false,
          message: '请输入简称',
          trigger: 'blur'
        }, {
          max: 100,
          message: '最多可输入100个字符',
          trigger: 'blur'
        }
      ],
      seq: [
        {
          required: false,
          message: '请输入排序号',
          trigger: 'blur'
        }
      ],
      state: [
        {
          required: true,
          message: '请选择状态（字典：FLOW_CATEGORY_STATE）',
          trigger: 'blur'
        }, {
          max: 10,
          message: '最多可输入10个字符',
          trigger: 'blur'
        }
      ],
      remark: [
        {
          required: false,
          message: '请输入备注',
          trigger: 'blur'
        }, {
          max: 500,
          message: '最多可输入500个字符',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(actionParam: string, rowParam?: FlowCategoryModel, parentParasms?: { pid: string }) {
      visible.value = true
      loading.value = false
      action.value = actionParam

      handleSearchTree()

      if (['edit', 'view'].indexOf(actionParam) > -1 && rowParam) {
        assign(dbForm, cloneDeep(rowParam))
      } else {
        assign(state, parentParasms)
      }
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 提交表单
     */
    function handleSubmit(isContinue: boolean) {
      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          assign(dbForm, {
            pid: arrayLastValue(state.pid)
          })

          if (action.value === 'add') {
            addFun(isContinue)
          } else {
            editFun()
          }
        } else {
          log.warn('流程分类', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(isContinue: boolean) {
      loading.value = true
      apiFlowCategorySave(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset(!isContinue)
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      apiFlowCategoryUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset(true)
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset(isClosed: boolean) {
      assign(dbForm, cloneDeep(defaultForm))
      if (isClosed) {
        emit('refreshTableData')
        visible.value = false
      }
    }

    //////////////////////////////////////////////////
    // 流程分类树
    //////////////////////////////////////////////////

    const treeData = ref()

    /**
     * 查询流程分类树
     */
    function handleSearchTree() {
      apiFlowCategorySearchTree({}).then((result) => {
        treeData.value = result.treeData
      })
    }

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      visible,
      action,
      title,
      state,
      dbFormRef,
      dbForm,
      rules,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset,
      treeData
    }
  }
})
